package com.itcam.daijia.rules.utils;

import org.kie.api.KieServices;
import org.kie.api.builder.KieBuilder;
import org.kie.api.builder.KieFileSystem;
import org.kie.api.builder.KieModule;
import org.kie.api.runtime.KieContainer;
import org.kie.api.runtime.KieSession;
import org.kie.internal.io.ResourceFactory;

public class DroolsHelper {

    // 规则文件DRL的路径
    private static final String RULES_CUSTOMER_RULES_DRL = "rules/FeeRule.drl";

    // 从DRL文件加载规则并返回KieSession
    public static KieSession loadForRule(String drlStr) {
        // 创建一个新的KieServices实例
        KieServices kieServices = KieServices.Factory.get();

        // 创建一个新的KieFileSystem实例
        KieFileSystem kieFileSystem = kieServices.newKieFileSystem();
        // 将DRL文件写入KieFileSystem
        kieFileSystem.write(
                ResourceFactory.newClassPathResource(drlStr));

        // 创建一个新的KieBuilder实例
        KieBuilder kb = kieServices.newKieBuilder(kieFileSystem);
        // 构建KieModule
        kb.buildAll();

        // 获取KieModule
        KieModule kieModule = kb.getKieModule();
        // 创建一个新的KieContainer实例
        KieContainer kieContainer = kieServices.newKieContainer(kieModule.getReleaseId());
        // 返回一个新的KieSession
        return kieContainer.newKieSession();
    }
}

